<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/6/20
 * Time: 20:19
 */

namespace ElementVip\JwOms\Handler;

use Anchu\Ftp\Facades\Ftp;
use Carbon\Carbon;
use ElementVip\JwOms\Models\OmsDownloadLog;
use ElementVip\JwOms\Models\OmsSyncLog;
use ElementVip\JwOms\Models\OmsUploadLog;
use Storage;

set_include_path(__DIR__ . '/phpseclib');
include('Net/SFTP.php');

abstract class AbstractOms
{
    protected $ftp;

    /*public function __construct()
    {

    }*/

    protected function connect()
    {
        for ($i = 0; $i < 3; $i++) {
            try {
                $this->ftp = new \Net_SFTP('121.41.172.108');
                if ($this->ftp->login('jw-iyoyo', 'qq6iiz4')) {
                    \Log::info('connect time:' . $i);
                    break;
                }
            } catch (\Exception $e) {
                \Log::info('ftp exception:' . $i . '===' . $e);
            }
            if ($i == 2) {
                exit('Login Failed e');
            }
        }


        /*$this->ftp = new \Net_SFTP('121.41.172.108');
        if (!$this->ftp->login('jw-iyoyo', 'qq6iiz4')) {
            exit('Login Failed');
        }*/
    }

    /**
     * 创建FTP目录
     * @param $dirName
     * @return bool
     */
    public function makeDir($dirName)
    {
        /*$this->ftp = Ftp::connection();
        $dirList = $this->ftp->getDirListing();
        \Log::info('获取到的目录' . json_encode($dirList));
        if ($dirList AND count($dirList) > 0 AND in_array($dirName, $dirList)) {
            return true;
        } else {
            return $this->ftp->makeDir($dirName);
        }*/

        $this->connect();
        $dirList = $this->ftp->nlist();
        \Log::info('sftp获取到的目录' . json_encode($dirList));
        if ($dirList AND count($dirList) > 0 AND in_array($dirName, $dirList)) {
            return true;
        } else {
            return $this->ftp->mkdir($dirName);
        }
    }

    public function uploadFile($local, $remote)
    {
        return $this->ftp->put($remote, $local, NET_SFTP_LOCAL_FILE);
    }

    public function downloadFile($local, $remote)
    {
        /*$this->ftp = Ftp::connection();
        return $this->ftp->uploadFile($local, $remote);*/

        $this->connect();
        return $this->ftp->get($remote, $local);

    }

    public function close()
    {
        // Ftp::disconnect();
    }

    /**
     * 上传文件
     * @param $type
     * @param $file_extend
     * @param $data
     */
    public function createFile($type, $file_extend, $data)
    {
        $fileDir = getFileDirPrefix($type);

        $filename = $type . '_' . Carbon::now()->format('YmdHms') . '.' . $file_extend;

        if (Storage::put('public/oms/upload/' . $fileDir . '/' . $filename, $data['data'])) {
            if ($this->makeDir($type)) {
                if ($this->uploadFile(storage_path('app/public/oms/upload/' . $fileDir . '/' . $filename), $fileDir . '/' . $filename)) {
                    OmsUploadLog::create([
                        'path' => '/storage/oms/upload/' . $fileDir . '/' . $filename,
                        'type' => $type,
                        'remote' => $fileDir . '/' . $filename,
                        'message' => getTypeText($type),
                        'last_tag' => $data['lastTag']
                    ]);
                } else {
                    OmsUploadLog::create([
                        'path' => '/storage/oms/upload/' . $fileDir . '/' . $filename,
                        'type' => $type,
                        'remote' => $fileDir . '/' . $filename,
                        'message' => getTypeText($type) . '【失败】',
                        'status' => 2
                    ]);
                }
            } else {
                OmsUploadLog::create([
                    'path' => '/storage/oms/upload/' . $fileDir . '/' . $filename,
                    'type' => $type,
                    'remote' => $fileDir . '/' . $filename,
                    'message' => '创建远程目录 ' . $type . ' 失败',
                    'status' => 2
                ]);
            }
            $this->close();
        }
    }


    /**
     * 下载文件
     * @param $type
     */
    public function downloadFiles($type)
    {
        /*$this->ftp = Ftp::connection();*/
        $this->connect();
        $fileDir = getFileDirPrefix($type);
        $fileList = [];
        if (Storage::makeDirectory('public/oms/download/' . $fileDir)) {   // 创建本地下载目录

            $files = $this->ftp->nlist($fileDir);      //获取FTP文件列表

            if ($files AND count($files) > 0) {
                if ($type == 'InvupStock' OR $type == 'Stock') {
                    $files = $this->filterFiles($files, $type);
                }

                foreach ($files as $key => $item) {
                    $filePath = $fileDir . '/' . $item;
                    $check = OmsDownloadLog::where('type', $type)->where('remote', $filePath)->where('status', 1)->first();
                    if (!$check) {
                        /*if ($this->ftp->downloadFile($filePath, storage_path('app/public/oms/download/') . $filePath)) {    //下载文件*/
                        if ($this->ftp->get($filePath, storage_path('app/public/oms/download/') . $filePath)) {
                            OmsDownloadLog::create([
                                'type' => $type,
                                'path' => '/storage/oms/download/' . $filePath,
                                'remote' => $filePath,
                                'message' => getTypeText($type),
                            ]);
                            $fileList[] = storage_path('app/public/oms/download/') . $filePath;
                        } else {
                            OmsDownloadLog::create([
                                'type' => $type,
                                'path' => '/storage/oms/download/' . $filePath,
                                'remote' => $filePath,
                                'message' => getTypeText($type) . '【失败】',
                                'status' => 2
                            ]);
                        }
                    }
                }
            }
            $this->close();
            return $fileList;
        }
        \Log::info('创建本地下载目录失败');
        $this->close();
        return [];
    }

    /**
     * 过滤库存文件：因为增量库存和总库存是同一个路径Stock，需要区分开来
     * @param $files
     */
    private function filterFiles($files, $type)
    {

        foreach ($files as $key => $item) {
            if ($type == 'InvupStock') //增量库存
            {
                if (!str_contains($item, 'INVUP')) {
                    unset($files[$key]);
                }
            } else {  //总库存
                if (!str_contains($item, 'IBAL')) {
                    unset($files[$key]);
                }
            }
        }
        return $files;
    }


}